//
//  ArticleCell.m
//  Molian
//
//  Created by wansong on 3/31/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "ArticleCell.h"
#import "MLTabBar.h"
#import "MLHomeViewController.h"
#import "CommentViewController.h"
#import "LoginViewController.h"

@implementation ArticleCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.is = NO;
        self.backgroundColor = RGBA(244, 244, 244, 1);
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell背景
        UIView *cellview = [[UIView alloc]initWithFrame:CGRectMake(10, 8, DeviceWidth-20, EqualHeight(260, 608, DeviceWidth-20))];
        cellview.clipsToBounds = NO;
        cellview.layer.masksToBounds = YES;//开启圆角
        [cellview.layer setCornerRadius:4];
        cellview.backgroundColor = [UIColor whiteColor];
        [cellview.layer setBorderColor:[RGBA(191, 191, 191, 1) colorWithAlphaComponent:1].CGColor];
        [cellview.layer setBorderWidth:0.3];
        [self.contentView addSubview:cellview];
        
        CGFloat CellHeight = cellview.bounds.size.height;
        CGFloat CellWidth = cellview.bounds.size.width;
        
        //推荐图片
        self.titleImage= [[UIImageView alloc]init];
        self.titleImage.frame = CGRectMake(0, 0, CellWidth, CellHeight);
        
        self.nImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)];
        self.nImageView.clipsToBounds = YES;
        self.nImageView.image = [UIImage imageNamed:@"home_-recommend_new_icon"];
        self.nImageView.hidden = YES;
        [self.titleImage addSubview:self.nImageView];
        
        
        self.titleImage.clipsToBounds = YES;
        [self.titleImage setContentMode:UIViewContentModeScaleAspectFill];
        [cellview addSubview:self.titleImage];
        
        
        UIImageView *cellbackground = [[UIImageView alloc]initWithFrame:CGRectMake(0, CellHeight-45, CellWidth, 45)];
        cellbackground.image = [UIImage imageNamed:@"profile_title_shadow"];
        cellbackground.alpha = 0.7;
        [cellview addSubview:cellbackground];
        
        //推荐标题
        self.titleLabel = [[UILabel alloc]init];
        self.titleLabel.frame = CGRectMake(5, CellHeight-40, CellWidth-10, 40);
        self.titleLabel.font = [UIFont fontWithName:FontName size:16];//改字体和大小
        self.titleLabel.textColor = [UIColor whiteColor];
        [cellview addSubview:self.titleLabel];
        
        //分享按钮
        //        self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        self.shareBtn.frame = CGRectMake(0, CellHeight-40, btnWidth, 40);
        //        [self.shareBtn setImage:[UIImage imageNamed:@"icon_forward"] forState:UIControlStateNormal];
        //        [self.shareBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        //        self.shareBtn.adjustsImageWhenDisabled = YES;
        //        [self.shareBtn addTarget:self action:@selector(goToShare) forControlEvents:UIControlEventTouchUpInside];
        //        [self labelStyle:self.shareBtn.titleLabel];
        //        [cellview addSubview:self.shareBtn];
        //
        //
        //        //评论按钮
        //        self.commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        self.commentBtn.frame = CGRectMake((CellWidth-btnWidth)/2, CellHeight-40, btnWidth, 40);
        //        [self.commentBtn setImage:[UIImage imageNamed:@"icon_comment"] forState:UIControlStateNormal];
        //        [self.commentBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        //        self.commentBtn.adjustsImageWhenDisabled = YES;
        //        [self.commentBtn addTarget:self action:@selector(goToComment) forControlEvents:UIControlEventTouchUpInside];
        //        [self labelStyle:self.commentBtn.titleLabel];
        //        [cellview addSubview:self.commentBtn];
        
        //        UIImageView * Like = [[UIImageView alloc]initWithFrame:CGRectMake(CellWidth-40, 10, 30, 30)];
        //       // Like.image = [UIImage imageNamed:@""];
        //        [cellview addSubview:Like];
        
        
        //喜欢按钮
        self.likeBtn = [[LikeButton alloc]initWithFrame:CGRectMake(CellWidth-110, 10, 100, 25)];
        self.likeBtn.isRead = YES;
        //        self.likeBtn.frame = CGRectMake(CellWidth-120, 10, 100, 40);
        //        [self.likeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //        self.likeBtn.adjustsImageWhenDisabled = YES;
         self.likeBtn.icon.frame = CGRectMake(self.likeBtn.frame.size.width-21, (self.likeBtn.frame.size.height-7)/2, 13, 7);
         self.likeBtn.icon.image = [UIImage imageNamed:@"阅读量"];
       
        [self.likeBtn addTarget:self action:@selector(likeArticle) forControlEvents:UIControlEventTouchUpInside];
        self.likeBtn.enabled = NO;
        //        [self labelStyle:self.likeBtn.titleLabel];
        [cellview addSubview:self.likeBtn];
        
        //        [self.likeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 20)];
        //        [self.likeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        
        //        NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:self.likeBtn.titleLabel.font,NSFontAttributeName,nil];
        //        CGSize size = [self.likeBtn.titleLabel.text sizeWithAttributes:dic];
        //        NSLog(@"%f",btnWidth-40);
        //        [self.likeBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
        
        
        CATransition *trans=[[CATransition alloc]init];
        [trans setType:kCATransitionReveal];
        [trans setSubtype:kCATransitionFromRight];
        [trans setDuration:0.5];
        [self.layer addAnimation:trans forKey:nil];
    }
    
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    //CGSize size =   [str sizeWithFont:label.font];
    //字典（key-value）
    
    NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:self.likeBtn.Title.font,NSFontAttributeName,nil];
    CGSize size = [self.likeBtn.Title.text sizeWithAttributes:dic];
    self.likeBtn.frame = CGRectMake(DeviceWidth - size.width - 60, 12, size.width + 30, 25);
    
}

//统一风格
-(UILabel *)labelStyle:(UILabel *)label
{
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont fontWithName:FontName size:11];//改字体和大小
    return label;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

#pragma mark - user interaction
// 喜欢文章
- (void)likeArticle {
    if (![Utils userinit:self.tabbar]) {
        return;
    }
    [ShareData shareData].isRecommend = YES;
    if (self.is) {
        //正在请求数据,不执行
    }else{
        self.is = YES;//开始请求数据
        if (!self.likeBtn.status) {
            MLArticleLike *like = [MLArticleLike object];
            like.user = [MLUser currentUser];
            like.article = self.article;
            [like saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                self.is = NO;//请求数据结束
                if (!error) {
                    NSInteger i = [self.likeBtn.Title.text integerValue];
                    if(i<0){
                        i = 0;
                    }
                    NSString *likecount = [NSString stringWithFormat:@"%ld",(long)i+1];
                    
                    self.likeBtn.Title.text = likecount;
                    [[ShareData shareData].likeArticlesDic setObject:likecount forKey:self.article.objectId];
                    [Utils savePassLoveArticleObjectID:self.article.objectId];
                    
                    
                    self.likeBtn.status = YES;
                    [self.likeBtn Like:YES Alpha:0.6];
                    [self.article incrementKey:@"likeCount" byAmount:[NSNumber numberWithInteger:+1]];
                    self.article.fetchWhenSave = true;
                    [self.article saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (!error) {
                            // article表增加一个喜欢的次数
                            // 添加到喜欢的列表里面
                        }
                    }];
                }
            }];
        }else{
            
            AVQuery *q = [MLArticleLike query];
            [q whereKey:@"user" equalTo:[MLUser currentUser]];
            [q whereKey:@"article" equalTo:self.article];
            [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSInteger count = [self.likeBtn.Title.text integerValue];
                if(error){
                    //错误
                    self.is = NO;//请求数据结束
                }else{
                    count --;
                    if(count<0){
                        count = 0;
                    }
                    self.is = NO;//请求数据结束
                    NSString *likecount = [NSString stringWithFormat:@"%ld",(long)count];
                    self.likeBtn.Title.text = likecount;
                    [[ShareData shareData].likeArticlesDic setObject:likecount forKey:self.article.objectId];
                    [Utils removeObjectForLoveArticleObjectID:self.article.objectId];
                    
                    self.likeBtn.status = NO;
                    [self.likeBtn Like:NO Alpha:0.6];
                    [self.article incrementKey:@"likeCount" byAmount:[NSNumber numberWithInteger:-1]];
                    self.article.fetchWhenSave = true;
                    [self.article saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (!error) {
                            
                            //    [homeView.likeArticles removeObject:a];
                            
                        }
                    }];
                    
                    
                }
                
                
            }];
        }
    }
}

@end
